package com.youlu.campus.service.course;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author : [dengbo]
 * @className : QueryWrapper
 * @description : [查询包装类]
 * @createTime : [2022/5/21 09:33]
 */
public class QueryWrapper extends Query{
    public QueryWrapper(){
        super();
    }

    public QueryWrapper select(String... fields) {
        if (ArrayUtils.isNotEmpty(fields)) {
            Arrays.stream(fields).forEach(this.fields()::include);
        }
        return this;
    }

    public QueryWrapper select(List<String> fields) {
        if (CollectionUtils.isNotEmpty(fields)) {
            fields.forEach(this.fields()::include);
        }
        return this;
    }

    public QueryWrapper where(String key, Object value) {
        this.addCriteria(Criteria.where(key).is(value));
        return this;
    }

    public QueryWrapper like(String k, Object v) {
        Pattern pattern = Pattern.compile("^.*" + v + ".*$", Pattern.CASE_INSENSITIVE);
        this.addCriteria(Criteria.where(k).regex(pattern));
        return this;
    }

    public QueryWrapper in(String k, Object... v) {
        this.addCriteria(Criteria.where(k).in(v));
        return this;
    }

    public QueryWrapper in(String k, Collection<?> v) {
        this.addCriteria(Criteria.where(k).in(v));
        return this;
    }

    public QueryWrapper leftLike(String k, String v) {
        Pattern pattern = Pattern.compile("^.*" + v, Pattern.CASE_INSENSITIVE);
        this.addCriteria(Criteria.where(k).regex(pattern));
        return this;
    }

    public QueryWrapper rightLike(String k, String v) {
        Pattern pattern = Pattern.compile(v + ".*$", Pattern.CASE_INSENSITIVE);
        this.addCriteria(Criteria.where(k).regex(pattern));
        return this;
    }

    public QueryWrapper page(int page, int pageSize) {
        page = page <= 1 ? 0 : page - 1;
        PageRequest pageRequest = PageRequest.of(page, pageSize);
        this.with(pageRequest);
        return this;
    }

    public QueryWrapper range(String key, Object left, Object right) {
        if (left == null && right == null) {
            return this;
        }
        if (left != null && right != null) {
            this.addCriteria(new Criteria().andOperator(Criteria.where(key).gte(left), Criteria.where(key).lte(right)));
            return this;
        }
        Criteria where = Criteria.where(key);
        if (left != null) {
            where.gte(left);
        }
        if (right != null) {
            where.lte(right);
        }
        this.addCriteria(where);
        return this;
    }
}
